package com.qk.management.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

import com.qk.common.PageResult;
import com.qk.common.constant.BusinessStatusConstants;
import com.qk.common.constant.ClueStatusConstants;
import com.qk.common.enums.LoginEnum;
import com.qk.common.enums.ParamEnum;
import com.qk.common.exception.CommonException;
import com.qk.common.util.JwtUtil;
import com.qk.domain.user.UserDO;
import com.qk.dto.user.UserDto;
import com.qk.dto.user.UserLoginDTO;
import com.qk.entity.Clue;
import com.qk.entity.User;


import com.qk.management.mapper.BusinessMapper;
import com.qk.management.mapper.ClueMapper;
import com.qk.management.mapper.UserMapper;
import com.qk.management.service.RoleService;
import com.qk.management.service.UserService;
import com.qk.vo.user.UserLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;


import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 用户服务实现类
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleService roleService;

    @Autowired
    private ClueMapper clueMapper;

    @Autowired
    private BusinessMapper businessMapper;

    private static final String DEFAULT_PASSWORD = "123";
    private static final Integer LOGIN_STATUS_UMNOMALL = 0;


    @Override
    public UserLoginVO login(UserLoginDTO dto) {

        if (BeanUtil.hasNullField(dto)) {
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        User dbUser = userMapper.getUserByUsername(dto.getUsername());
        if (Objects.isNull(dbUser)) {
            CommonException.throwCommonException(LoginEnum.LOGIN_ERROR);
        }

        if (Objects.equals(dbUser.getStatus(), LOGIN_STATUS_UMNOMALL)) {
            CommonException.throwCommonException(LoginEnum.LOGIN_STATUS_ERROR);
        }

        if (!ObjectUtil.equals(DigestUtils.md5DigestAsHex(dto.getPassword().getBytes()), dbUser.getPassword())) {
            CommonException.throwCommonException(LoginEnum.LOGIN_ERROR);
        }


        return UserLoginVO.builder()
                .id(dbUser.getId())
                .username(dbUser.getUsername())
                .name(dbUser.getName())
                .image(dbUser.getImage())
                .roleLabel(roleService.getRoleById(dbUser.getRoleId()).getLabel())
                .token(JwtUtil.generateToken(new HashMap<>(Map.of("id", dbUser.getId(), "username", dbUser.getUsername()))))
                .build();
    }


    @Override
    public List<User> getUserByDeptId(Integer id) {
        return userMapper.selectUserByDept(id);
    }


    @Override
    public List<User> getUserByRole(String role) {
        return userMapper.selectUserByRole(role);
    }


    @Override
    public List<User> listAllUsers() {
        return userMapper.selectAllUser();
    }


    @Override
    public void updateUser(User user) {
        // 设置更新时间为当前时间
        user.setUpdateTime(LocalDateTime.now());
        // 密码加密处理
        user.setPassword(DigestUtils.md5DigestAsHex((user.getPassword()+DEFAULT_PASSWORD).getBytes()));
        user.setPassword(DigestUtils.md5DigestAsHex((user.getPassword() + "123").getBytes()));
        userMapper.update(user);
    }


    @Override
    public User getUserById(Integer id) {
        return userMapper.select(id);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteUserById(List<Integer> ids) {
        // 参数校验
        if (ids == null || ids.isEmpty()) {
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }

        // 删除用户时，将其下方管理的线索或是客户商机等改为未分配状态
        clueMapper.updateByUserIds(ids,LocalDateTime.now(), ClueStatusConstants.WAIT_ALLOCATION);

        businessMapper.updateByUserIds(ids,LocalDateTime.now(), BusinessStatusConstants.WAIT_ALLOCATION);

        userMapper.deleteByIds(ids);
    }


    @Override
    public void addUser(User user) {

        boolean hasNull = BeanUtil.hasNullField(user, "id", "password", "roleId", "deptId", "image", "remark", "updateTime", "createTime");
        if (hasNull) {
            throw new RuntimeException("参数错误");
        }

        user.setPassword(DigestUtils.md5DigestAsHex((user.getUsername() + "123").getBytes()));
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        userMapper.insert(user);
    }


    /**
     * 条件分页查询用户列表
     */
    @Override
    public PageResult<UserDO> getUsers(UserDto userDto) {
        // 开始分页
        PageHelper.startPage(userDto.getPage(), userDto.getPageSize());

        // 执行查询
        List<UserDO> users = userMapper.getUsers(userDto);

        // 获取分页信息
        Page<UserDO> pageInfo = (Page<UserDO>) users;

        // 封装成 PageResult 对象
        return new PageResult<>(pageInfo.getTotal(), pageInfo.getResult());
    }


}